from flask_restful import Resource
from flask_restful.reqparse import RequestParser
from flask_restful import inputs
from flask import g, current_app
from cache import article
from cache import user
from cache.article import ArticleInfoCache


class SearchResource(Resource):
    """
    搜索结果
    """
    def get(self):
        """
        获取搜索结果
        """
        # 解析参数
        qs_parser = RequestParser()
        qs_parser.add_argument('q', type=inputs.regex(r'^.{1,50}$'), required=True, location='args')
        qs_parser.add_argument('page', type=inputs.positive, default=1, required=False, location='args')  # 当前页码
        qs_parser.add_argument('per_page', type=int, default=10, required=False, location='args')  # 每页条数
        args = qs_parser.parse_args()
        q = args.q
        page = args.page
        per_page = args.per_page

        body = {
            "_source": False,
            "from": (page - 1) * per_page,  # 0  10  20  30
            "size": per_page,  # 10
            'query': {
                "bool": {
                    "must": {
                        "match": {
                            "_all": q
                        }
                    },
                    "filter": {
                        "term": {
                            "status": 2
                        }
                    }
                }
            }
        }

        # 进行ES查询
        ret = current_app.es.search(index='articles', doc_type='article', body=body)
        articles = ret['hits']['hits']

        total_count = ret['hits']['total']

        results = []
        for article in articles:
            # 根据id查询基础数据库
            acticle_dict = ArticleInfoCache(article['_id']).get()
            results.append(acticle_dict)

        # 存储搜索历史 在redis中进行了持久化
        if g.user_id and page == 1:
            user.UserSearchingHistoryStorage(g.user_id).save(q)

        # 包装为json返回
        resp = {
            "total_count":total_count,
            "page": page,
            "per_page": per_page,
            "results": results
        }
        return resp


class SuggestionResource(Resource):
    """
    联想建议
    """
    def get(self):
        """
        获取联想建议
        """
        # 解析参数
        qs_parser = RequestParser()
        qs_parser.add_argument('q', type=inputs.regex(r'^.{1,500}$'), required=True, location='args')
        args = qs_parser.parse_args()
        q = args.q

        # 先尝试自动补全建议查询
        query = {
            'from': 0,
            'size': 10,
            '_source': False,
            'suggest': {
                'word-completion': {
                    'prefix': q,
                    'completion': {
                        'field': 'suggest'
                    }
                }
            }
        }
        ret = current_app.es.search(index='completions', body=query)
        options = ret['suggest']['word-completion'][0]['options']

        # 如果没得到查询结果，进行纠错建议查询
        if not options:
            query = {
                'from': 0,
                'size': 10,
                '_source': False,
                'suggest': {
                    'text': q,
                    'word-phrase': {
                        'phrase': {
                            'field': '_all',
                            'size': 1
                        }
                    }
                }
            }
            ret = current_app.es.search(index='articles', doc_type='article', body=query)
            options = ret['suggest']['word-phrase'][0]['options']

        results = []
        for option in options:
            if option['text'] not in results:
                results.append(option['text'])

        return {'options': results}

